<template>
    <div>
        <Header></Header>
        <div class="main">
            <div class="banner">
                <img style="width: 100%" src="https://img.js.design/assets/img/617766b867e5da8dd2a409b5.png" alt="">
            </div>
            <div class="breadcrumb">
                <el-breadcrumb :separator-icon="'ArrowRightBold'">
                    <el-breadcrumb-item class="link" @click="toIndex">首页</el-breadcrumb-item>
                    <el-breadcrumb-item class="link" @click="toQuestionBack">我的题库</el-breadcrumb-item>
                    <el-breadcrumb-item class="link" @click="toBack">{{subject_name}}</el-breadcrumb-item>
                    <el-breadcrumb-item class="link">每日一练</el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div style="align-items: center" v-if="subjects">
                <el-row :gutter="20" style="margin-right: 0">
                    <el-col :span="17">
                        <el-card class="box-card">
                            <template #header>
                                <el-row>
                                    <el-col :span="6">
                                        <span v-if="active_subject.parent_id">
                                            第{{active_subject.parent_sort}}-{{active_subject.sort}}题，{{active_subject.type_name}}
                                        </span>
                                        <span v-else>
                                            第{{active_subject.sort}}题，{{active_subject.type_name}}
                                        </span>
<!--                                        <span>{{`第${active_idx+1}题，${active_subject.type_name}`}}</span>-->
                                    </el-col>
                                    <el-col :span="18">
                                        <div class="card-header">
                                            <div style="display: flex;align-items: center;justify-content: space-between;width: 100%">
                                                <div>
                                                    <el-button-group>
                                                        <el-button :type="active_subject.flag?'primary':''"
                                                                   size="small"
                                                                   @click="active_subject.flag=!active_subject.flag">
                                                            <el-icon>
                                                                <Flag/>
                                                            </el-icon>
                                                          &nbsp;{{active_subject.flag?' 取消':'标记'}}
                                                        </el-button>
                                                        <el-button @click="addLike(active_subject.topic_id)" size="small" :type="active_subject.is_collect?'primary':''">
                                                            <el-icon><StarFilled /></el-icon>&nbsp;收藏
                                                        </el-button>
                                                        <el-button size="small" @click="checked"><el-icon><View /></el-icon>&nbsp;解析</el-button>
                                                    </el-button-group>
                                                </div>
                                            </div>
                                        </div>
                                    </el-col>
                                </el-row>

                            </template>
                          <div>
                            <el-button size="small" style="margin-right: 15px;margin-bottom: 15px;" v-if="active_subject && active_subject.parent_id" type="primary" @click="isCase = !isCase">查看题目背景</el-button>
                          </div>
                            <Question
                                    :subject="active_subject"
                                    v-model:user_answer="active_subject.user_answer"
                                    :mode="mode"
                                    @checked="checked">
                            </Question>
                            <img class="question-icon" src="../../../assets/tiku/mryl-icon.png" alt="">
                        </el-card>
                        <div style="margin-top: 30px">
                            <el-button-group>
                                <el-button type="primary" @click="pre" :disabled="active_idx<=0">
                                    {{'< 上一题'}}
                                </el-button>
                                <el-button type="primary" @click="next" :disabled="active_idx>=subjects.length-1">
                                    {{'下一题 >'}}
                                </el-button>
                            </el-button-group>
<!--                            <el-button type="primary" @click="submit">Primary</el-button>-->
                        </div>
<!--                        <div v-html="leads[active_subject.parent_id]"></div>-->
                    </el-col>
                    <el-col :span="7">
                        <div class="grid-content bg-purple-dark"/>
                        <div class="button-group">
                            <div style="display: flex">
                                <el-button size="small" plain type="primary" :icon="'Tickets'" style="margin-right: 16px" @click="tableOfRates = !tableOfRates">税率表</el-button>
                                <el-button size="small" plain type="primary" :icon="'Search'" @click="showCalculator">计算器</el-button>
                            </div>
                        </div>
                        <div>
                            <Picker
                                    :subjects="subjects"
                                    v-model:index="active_idx"
                                    :height="'300'"
                                    :mode="mode">
                            </Picker>
                        </div>
                        <div>
                            <el-button v-if="mode == 'train'" type="primary" @click="submitAnswerFun" class="submit-button">交卷并查看结果</el-button>
                        </div>
                    </el-col>
                </el-row>
            </div>
            <el-empty v-else style="height:560px;" :image-size="200" description="暂无数据" />
        </div>
        <div v-if="active_subject && active_subject.parent_id">
            <Case v-show="isCase" @anliClose="anliClose" :isShowCase="active_subject && active_subject.parent_id ? true:false" :caseContent="active_subject && active_subject.parent_id ? leads[active_subject.parent_id] :''"></Case>
        </div>
      <TableOfRates v-model="tableOfRates" :img-url="imgUrl"></TableOfRates>
        <Dialog :dialogVisible="dialogVisible" @dialogEnd="dialogEnd"></Dialog>
        <div class="parent" v-if="isCalculator">
            <Vue3DraggableResizable
                    :initW="280"
                    :minW="220"
                    v-model:x="x"
                    v-model:y="y"
                    v-model:w="w"
                    v-model:h="h"
                    v-model:active="active"
                    :draggable="true"
                    :resizable="true"
                    @activated="print('activated')"
                    @deactivated="print('deactivated')"
                    @drag-start="print('drag-start')"
                    @resize-start="print('resize-start')"
                    @dragging="print('dragging')"
                    @resizing="print('resizing')"
                    @drag-end="print('drag-end')"
                    @resize-end="print('resize-end')"
            >
                <Calculator @closeCalcuator="closeCalcuator"></Calculator>
            </Vue3DraggableResizable>
        </div>
        <staticFooter></staticFooter>
    </div>
</template>

<script>
import TableOfRates from "@/components/TableOfRates";
    import Dialog from '@/components/dialog/index'
    import Case from "../../../components/Case";
    import staticFooter from "../../../components/staticFooter";
    import {submit_result,submitAnswer} from "../../../hock/submit_question/submit_questions";
    import Calculator from "../../../components/calculator/Calculator";
    import goBackHistory from "../../../utils/hook/goBackHistory";
    import Question from "../../../components/Question/Question";
    import Picker from "../../../components/Picker/Picker";
    import comm_chapter from "../../../hock/composables/comm_chapter";

    import {Flag} from '@element-plus/icons-vue'
    import {ref, watch,onBeforeUnmount} from 'vue'
    import Header from "../../../components/Header";
    import {useRoute, useRouter} from "vue-router";
    import {reactive,toRefs} from 'vue'
    import {exerciseMessage, meCollectORCancel, taxRateTable} from "../../../api/api";
    import source_to_subjects from "../../../hock/public/source_to_subjects";
    import {ElMessageBox,ElMessage} from 'element-plus'
    import {meCollect} from "../../../utils/hook/addLike/meCollect";
    export default {
        name: "index",
        setup() {
            let route = useRoute();
            let router = useRouter();
            let data = reactive({
                x: 100,
                y: 100,
                h: 100,
                w: 100,
                active: false,
                isCalculator:false,
                id:null,
                subject_name:'',
                ques_list:[],
                mode:'train',
                stateCode:0,
                isCase:false,
                tableOfRates:false,
                dialogVisible:false
            })
            data.id = route.params.id;
            data.subject_name = route.params.subject_name;
            data.stateCode = route.params.state;
            data.mode = data.stateCode == 0 ? 'train':'analysis'

            const active_idx = ref(0)
            const active_subject = ref(null)
            const {source, subjects, leads} = comm_chapter('exerciseMessage',{id:data.id});
            let setTimer = setInterval(() =>{
                try {
                    source.value.useTime = source.value.useTime ? source.value.useTime : 0;
                    source.value.useTime ++
                }catch (e) {

                }
            },1000)

            let anliClose = () =>{
                data.isCase = false
            }
            let sumbmitResult = (result) =>{
                console.log('result',result.res)
                let {correctS,correctNum,mistakeNum,unansweredNum} = result.res.data;
                data.correctS = correctS;
                data.correctNum = correctNum;
                data.answer = (correctNum+mistakeNum+unansweredNum) - unansweredNum;
                const subjects_leads = source_to_subjects(result.res.data);
                console.log('subjects_leads',subjects_leads)
                subjects.value = subjects_leads.subjects
                leads.value = subjects_leads.leads
                data.mode = 'analysis'
                clearInterval(setTimer)
            }
            let submitAnSwerLogs = (data) =>{
                const subjects_leads = source_to_subjects(data);
                subjects.value = subjects_leads.subjects
                leads.value = subjects_leads.leads
                data.mode = 'analysis'
                console.log('提交',subjects_leads,data.mode)
            }

            let dialogEnd = (params) =>{
                data.dialogVisible = params;
                submit();
            }

            let submit = async () => {
                    let answerSheet = {
                        state:1,
                        id:source.value.id,
                        index:active_idx.value,
                        useTime: source.value.useTime,
                        answerLogs:answerLogs()
                    }
                    let result = await submitAnswer(answerSheet,'exerciseSubmit');
                    sumbmitResult(result)
                }

            let submitAnswerFun = () =>{
                ElMessageBox.confirm(
                    '童鞋,请您确认是否需要提交试卷',
                    '温馨提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                )
                    .then(() => {
                        data.dialogVisible = true
                    })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '已取消',
                        })
                    })
            }

            let closeSubmit = async () =>{
                let answerSheet = {
                    state:0,
                    id:source.value.id,
                    index:active_idx.value,
                    useTime: source.value.useTime,
                    answerLogs:answerLogs()
                }
                let result = await submitAnswer(answerSheet,'exerciseSubmit');
                console.log(result)
                window.removeEventListener('beforeunload',() =>{});
            }
            window.addEventListener('beforeunload', closeSubmit);

            let toIndex = () =>{
                if(data.mode != 'analysis'){
                    ElMessageBox.confirm(
                        '童鞋，您的题目还没有交卷哦，确定要退出吗？',
                        '温馨提示',
                        {
                            confirmButtonText: '保存并退出',
                            cancelButtonText: '继续做题',
                            type: 'warning',
                        }
                    )
                        .then(() => {
                            closeSubmit();
                            router.push({name:'index'})
                        })
                        .catch(() => {
                        })
                }else{
                    router.push({name:'index'})
                }
            }
            let toQuestionBack = () =>{
                if(data.mode != 'analysis'){
                    ElMessageBox.confirm(
                        '童鞋，您的题目还没有交卷哦，确定要退出吗？',
                        '温馨提示',
                        {
                            confirmButtonText: '保存并退出',
                            cancelButtonText: '继续做题',
                            type: 'warning',
                        }
                    )
                        .then(() => {
                            closeSubmit();
                            router.push({name:'MyQuestionBank'})
                            let urlParams = goBackHistory.return_history();
                            router.push({name:urlParams.name,params:urlParams.params})

                        })
                        .catch(() => {

                        })
                }else{
                    router.push({name:'MyQuestionBank'})
                    let urlParams = goBackHistory.return_history();
                    router.push({name:urlParams.name,params:urlParams.params})
                }
            }
            onBeforeUnmount(() =>{
                closeSubmit();
            })

            let answerLogs = () => {
                let answerLogs = [];
                for (let item of subjects.value) {
                    if (item.user_answer) {
                        answerLogs.push({id: item.id, answer: item.user_answer.split('')});
                    }
                }
                return answerLogs;
            }

            //添加或取消收藏
            let addLike = (id) =>{
                active_subject.value.is_collect = !active_subject.value.is_collect;
                meCollect(id);
            }

            watch(active_idx, () => {
                active_subject.value = subjects.value[active_idx.value]
            })
            watch(source, () => {
                active_subject.value = subjects.value[active_idx.value]
                data.mode = source.value['state'] ? 'analysis':'train'
            })
            const checked = () => {
                active_subject.value.checked = true
            }
            const next = () => {
                active_idx.value = (active_idx.value + 1) % subjects.value.length
            }
            const pre = () => {
                active_idx.value -= 1
            }

            let showCalculator = () =>{
                data.isCalculator = !data.isCalculator
            }

            let print = (val) => {
                console.log(val)
            }

            let toBack = () =>{
                if(data.mode != 'analysis'){
                    ElMessageBox.confirm(
                        '童鞋，您的题目还没有交卷哦，确定要退出吗？',
                        '温馨提示',
                        {
                            confirmButtonText: '保存并退出',
                            cancelButtonText: '继续做题',
                            type: 'warning',
                        }
                    )
                        .then(() => {
                            closeSubmit();
                            let urlParams = goBackHistory.return_history();
                            router.push({name:urlParams.name,params:urlParams.params})
                        })
                        .catch(() => {

                        })
                }else{
                    let urlParams = goBackHistory.return_history();
                    router.push({name:urlParams.name,params:urlParams.params})
                }
            }

          const closeCalcuator = (param) =>{
            data.isCalculator = param;
          }

            let imgUrl = ref('')
            let getTaxRateTable = () =>{
                taxRateTable().then(res =>{
                    console.log(res)
                    imgUrl.value = res.data[0]
                })
            }
            getTaxRateTable();
            return {
              closeCalcuator,
                dialogEnd,
                imgUrl,
                anliClose,
                addLike,
                toIndex,
                toQuestionBack,
                closeSubmit,
                sumbmitResult,
                submitAnswerFun,
                print,
                showCalculator,
                submitAnSwerLogs,
                toBack,
                ...toRefs(data),
                active_idx,
                active_subject,
                source,
                subjects,
                checked,
                next,
                pre,
                submit,
                leads,
            }
        },
        components:{
          TableOfRates,
            Header,
            Question,
            Picker,
            Calculator,
            staticFooter,
            Case,
            Dialog
        }
    }
</script>

<style>
    .button-group .el-button{
        width: 48%;
    }
</style>

<style scoped>
    .box-card{
        position: relative;
    }
    .question-icon{
        position: absolute;
        top: 40%;
        right: 0%;
        transform: translate(-10%,-10%);
    }
    .submit-button{
        margin-top: 10px;
        width:100%;
    }
    .card-header{
        display: flex;
        justify-content: flex-end;
        align-items: center;
    }
    .parent {
        width: 200px;
        height: 200px;
        position: absolute;
        top: 0px;
        right: 200px;
        user-select: none;
    }
    .button-group{
        display: flex;
        justify-content: center;
        margin-bottom: 20px;
    }
    .button-group div{
        width: 100%;
    }
    .link{
        cursor: pointer;
    }
    .link:hover{
        color: skyblue;
    }
    .main{
        margin: 0 auto;
        margin-top: 75px;
        width: 75rem;
        margin-bottom: 60px;
    }
    .breadcrumb{
        height: 40px;
        display: flex;
        align-items: center;
    }
    .banner{
        width: 100%;
        height: 15rem;
        position: relative;
        overflow: hidden;
        border-top-right-radius: 10px;
        border-top-left-radius: 10px;
    }
    .banner > img {
        position: absolute;
        top: -100%;

    }
</style>
